package com.nefu.store.user.service.impl;

import cn.hutool.crypto.SmUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nefu.store.common.exception.user.UserCredentialException;
import com.nefu.store.common.exception.user.UserRegistryException;
import com.nefu.store.common.exception.user.UsernameEmptyException;
import com.nefu.store.common.exception.user.UsernameNotFoundException;
import com.nefu.store.domain.entity.User;
import com.nefu.store.tools.util.BloomFilterUtil;
import com.nefu.store.tools.util.JwtUtils;
import com.nefu.store.user.mapper.UserMapper;
import com.nefu.store.user.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<User> findAllUser(){
        return userMapper.selectList(null);
    }

    @Override
    public User login(String username, String password) {

//        用户名为空
        if(Objects.isNull(username)||username.isEmpty())
        {
            throw new UsernameEmptyException("用户名为空异常，登录失败");
        }

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));

        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名不存在异常，登录失败！");
        }
        String cpass = SmUtil.sm3(password);
        if(!cpass.equals(user.getPassword())){
            throw new UserCredentialException("用户名或密码错误，登录失败！");
        }



        return user;

    }
    @SneakyThrows
    @Override
    public void register(User user) {
        String username = user.getUsername();
        boolean isExist = BloomFilterUtil.getInstance().contains(username);

        // 用户名已存在
        if (isExist) throw new UserRegistryException("用户注册异常，用户名已存在");

        // 将密码加密
        String newP = SmUtil.sm3(user.getPassword());
        user.setPassword(newP);

        // 创建者
        user.setUpdateby("admin");

        // 加入数据库
        userMapper.insert(user);

        // 将username加入布隆过滤器
        BloomFilterUtil.getInstance().add(username);

        // 生成token
        String token = JwtUtils.createToken(user.getId(), user.getRole());

        // 序列化user数据
        ObjectMapper mapper = new ObjectMapper();
        mapper.findAndRegisterModules();
        String userStr = mapper.writeValueAsString(user);

        // 将token和user键值对加入redis数据库
        stringRedisTemplate.opsForValue().set(token, userStr, 2, TimeUnit.DAYS);


    }


}
